package com.zlzlib.libindex.decoration;

import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import java.util.ArrayList;
import java.util.List;

/**
 * Created by zlz on 2019/10/31.
 * RecyclerView   LinearLayoutManager  分组头部 只有顶部悬浮
 */
public abstract class BaseHeadViewDecoration<T extends TitleTextInterface> extends RecyclerView.ItemDecoration implements RecyclerView.OnItemTouchListener {

    protected List<T> data;
    //RecyclerView 头部有多少  要去除
    private int mHeaderViewCount = 0;
    private int mOrientation = LinearLayoutManager.VERTICAL;
    private View drawView;
    protected RecyclerView recyclerView;
    //点击
    private final GestureDetector mTapDetector;
    private Rect rectHead;

    //需要绘制的头部
    protected abstract View getDrawView(int position, RecyclerView parent);

    protected abstract int getOutRectHeight();

    public BaseHeadViewDecoration(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
        this.data = new ArrayList<>();
        recyclerView.addOnItemTouchListener(this);
        mTapDetector = new GestureDetector(recyclerView.getContext(), new SingleTapDetector());
    }

    public BaseHeadViewDecoration setData(List<T> data) {
        this.data.clear();
        this.data.addAll(data);
        return this;
    }

    public BaseHeadViewDecoration setHeaderViewCount(int mHeaderViewCount) {
        this.mHeaderViewCount = mHeaderViewCount;
        return this;
    }

    public void setOrientation(int mOrientation) {
        this.mOrientation = mOrientation;
    }

    public int getHeaderViewCount() {
        return mHeaderViewCount;
    }

    //绘制悬停的部分
    @Override
    public void onDrawOver(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.onDrawOver(c, parent, state);
        int position = ((LinearLayoutManager) (parent.getLayoutManager())).findFirstVisibleItemPosition();

        position -= getHeaderViewCount();
        if (data == null || data.isEmpty() || position > data.size() - 1 || position < 0 || !data.get(position).isShowTitle()) {
            return;
        }
        String title = data.get(position).getTitle();
        // View child = parent.getChildAt(pos);有时候child为空，
        // 所以将 child = parent.getChildAt(pos)。-》 parent.findViewHolderForLayoutPosition(pos).itemView
        View child = parent.findViewHolderForLayoutPosition(position + getHeaderViewCount()).itemView;
        if (child == null) {
            return;
        }
        drawView = getDrawView(position, parent);
        rectHead = new Rect(0, 0, drawView.getWidth(), drawView.getHeight());
        //定义一个flag，Canvas是否位移过的标志
        boolean flag = false;
        if (data.size() > position + 1) {
            //当前第一个可见的Item的tag，不等于其后一个item的tag，说明悬浮的View要切换了
            if (null != title && !title.equals(data.get(position + 1).getTitle())) {
                if (mOrientation == LinearLayoutManager.HORIZONTAL) {
                    //当前移动的绘制的view大小
                    int viewSize = drawView.getWidth();
                    //左右滑动的时候一样
                    int tran = child.getWidth() + child.getLeft();
                    if (child.getWidth() + child.getLeft() < viewSize) {
                        c.save();//每次绘制前 保存当前Canvas状态，
                        flag = true;
                        //左滑时，将canvas左移 （x为负数） ,
                        c.translate(tran - viewSize, 0);
                    }
                    rectHead = new Rect(0, 0, tran, drawView.getHeight());
                } else {
                    //当前移动的绘制的view大小
                    int viewSize = drawView.getHeight();
                    //当第一个可见的item在屏幕中还剩的高度小于title区域的高度时，我们也该开始做悬浮Title的“交换动画”
                    int tran = child.getHeight() + child.getTop();
                    if (tran < viewSize) {
                        c.save();//每次绘制前 保存当前Canvas状态，
                        flag = true;
                        //上滑时，将canvas上移 （y为负数） ,所以后面canvas 画出来的Rect和Text都上移了，有种切换的“动画”感觉
                        c.translate(0, tran - viewSize);
                    }
                    rectHead = new Rect(0, 0, drawView.getWidth(), tran);
                }
            }
        }
        //绘制图像
        if (drawView != null) {
            drawView.draw(c);
        }
        if (flag) c.restore();//恢复画布到之前保存的状态
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int position = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();
        position -= getHeaderViewCount();
        //第一个才设置
        if (position == 0) {
            outRect.set(0, getOutRectHeight(), 0, 0);
        }
    }

    @Override
    public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
        //将事件交给GestureDetector类进行处理，通过onSingleTapUp返回的值，判断是否要拦截事件
        boolean tapDetectorResponse = this.mTapDetector.onTouchEvent(e);
        if (tapDetectorResponse) {
            return true;
        }
        return false;
    }

    @Override
    public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
    }

    private class SingleTapDetector extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return onHeadClick(e);
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            return onHeadClick(e);
        }

        private boolean onHeadClick(MotionEvent e) {
            //根据点击的坐标查找是不是点击在header的区域
            if (drawView != null && rectHead != null && rectHead.contains((int) e.getX(), (int) e.getY())) {
                drawView.performClick();
                recyclerView.playSoundEffect(SoundEffectConstants.CLICK);
                drawView.onTouchEvent(e);
                return true;
            }
            return false;
        }
    }
}
